package jmine.tec.utils.collection;

import java.io.Serializable;
import java.util.AbstractSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Implementacao de {@link Set} {@link Serializable} que considera dois objetos iguais quando sao exatamente o mesmo objeto
 * 
 * @author takeshi
 * @param <E> o tipo do elemento contido
 */
public class IdentityHashSet<E> extends AbstractSet<E> implements Set<E>, Serializable {
    private static final int INITIAL_CAPACITY = 10;

    private final Map<E, Object> map;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object[0];

    /**
     * C'tor
     */
    public IdentityHashSet() {
        this(INITIAL_CAPACITY);
    }

    /**
     * @param size int
     */
    public IdentityHashSet(int size) {
        this.map = new IdentityHashMap<E, Object>(size);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Iterator<E> iterator() {
        return this.map.keySet().iterator();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int size() {
        return this.map.size();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isEmpty() {
        return this.map.isEmpty();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean contains(Object o) {
        return this.map.containsKey(o);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean add(E e) {
        return this.map.put(e, PRESENT) == null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean remove(Object o) {
        return this.map.remove(o) != null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void clear() {
        this.map.clear();
    }
}
